<template>
  <div class="flex flex-col h-full">
    <vxe-card title="" class="w-full" :border="false">
      <AuForm ref="formRef" :formList="formList" @submit="search" />
    </vxe-card>

    <div class="flex-grow overflow-hidden mt-[16px]">
      <AuTable ref="tableRef" v-bind="gridOption" @actionClick="actionClick" />
    </div>

    <StoreModal
      v-model:showModal="showModal"
      :storeData="storeData"
      @handleConfirm="handleConfirm"
    />

    <UploadModal
      v-model="showUploadModal"
      @handleConfirm="handleUploadConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { AuTable } from "@/components/AuTable";
import { AuForm } from "@/components/AuForm";
import {
  ACTION_TYPE,
  ObjectProps,
  PropDefines
} from "@/components/AuTable/type";
import {
  addStore,
  delStore,
  getGroupList,
  getStoreList,
  StoreProp,
  updStore,
  updStoreStatusStore
} from "@/api/teaInfuser/store";
import { handleTree } from "@/utils/tree";
import StoreModal from "@/views/teaInfuser/device/deviceManage/StoreModal.vue";
import { getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import { storeGroupSelect } from "@/utils/formSelect";
import { useRouter } from "vue-router";
import UploadModal from "@/views/teaInfuser/store/storeManage/uploadModal.vue";
import { formulaVerGetList } from "@/api/teaInfuser/formula";
import { useI18n } from "vue-i18n";

defineOptions({ name: "StoreManage" });

const { proxy } = getCurrentInstance();
const router = useRouter();
const { t } = useI18n();

// region 声明ref变量集合
const formList = ref([
  {
    type: "input",
    key: "name",
    label: "store_manage.form.store_name",
    placeholder: "store_manage.form.enter_store_name"
  },
  () => storeGroupSelect("group_idlist", {}, true),
  {
    type: "select",
    key: "version",
    label: "store_manage.form.formula_version",
    placeholder: "store_manage.form.select_formula_version",
    valueKey: "id",
    labelKey: "name",
    filterable: true,
    options: []
  }
]);
const gridOption = reactive<PropDefines>({
  isServerPage: true,
  showCheckbox: true,
  columns: [
    {
      field: "name",
      title: "store_manage.form.store_name",
      showOverflow: false
    },
    { field: "detail_address", title: "store_manage.form.store_address" },
    { field: "operator", title: "store_manage.form.store_manager" },
    { field: "device_num", title: "store_manage.form.device_count" },
    { field: "device_locknum", title: "store_manage.form.locked_device_count" },
    {
      field: "group_name",
      title: "store_manage.form.group",
      formatter: ({ cellValue }) =>
        cellValue ? cellValue : t("store_manage.form.national"),
      exportMethod: ({ row }) => {
        return row.group_name
          ? row.group_name
          : t("store_manage.form.national");
      }
    },
    {
      field: "store_status",
      title: "store_manage.form.store_status",
      formatter: ({ cellValue }) =>
        cellValue
          ? t("store_manage.form.closed")
          : t("store_manage.form.operating"),
      exportMethod: ({ row }) => {
        return row.store_status
          ? t("store_manage.form.closed")
          : t("store_manage.form.operating");
      }
    }
  ],
  actions: [
    ACTION_TYPE.EDIT,
    ACTION_TYPE.TADD,
    ACTION_TYPE.TDELETE,
    ACTION_TYPE.UPLOAD
  ],
  operateTools: [
    {
      icon: "",
      key: ACTION_TYPE.DELETE,
      name: "store_manage.form.pull_store"
    },
    {
      icon: "",
      key: ACTION_TYPE.VIEW,
      name: "store_manage.form.view_device"
    }
  ],
  dataSource: [],
  fetchConfig: {
    query: {
      service: (params: ObjectProps) => {
        return getStoreList(params);
      },
      param: () => {
        const { group_idlist, ...rest } = formRef.value.getFormData();
        const list = [];
        if (group_idlist?.length) {
          for (const id of group_idlist) {
            list.push({
              group_id: id
            });
          }
        }
        return {
          ...rest,
          group_idlist: JSON.stringify(list)
        };
      }
    }
  }
});

const showModal = ref(false);
const showUploadModal = ref(false);
const storeData = ref<Partial<StoreProp>>({});

const formRef = ref();
const tableRef = ref();
// endregion

// region 公共方法的集合
const getTreeSelect = async () => {
  const response = await getGroupList({ size: 0 });
  if (response.data != null) {
    const treeData = handleTree(response.data, "id", "parent_id");
    formRef.value.setFormProps("group_idlist", {
      data: treeData
    });
  }
};

function multiDelete() {
  if (!tableRef.value.getCheckboxRecords().length) {
    ElMessage({
      message: t("store_manage.form.select_delete"),
      type: "warning"
    });
    return;
  }
  proxy.$auMessageBox
    .confirm(t("store_manage.form.confirm_delete"), t("notice.title"), {
      type: "error"
    })
    .then(() => {
      const delList = tableRef.value
        .getCheckboxRecords()
        .map((v: StoreProp) => ({
          id: v.id
        }));
      delStore({ delList: JSON.stringify(delList) }).then(res => {
        ElMessage({
          message: t("notice.delete_success"),
          type: "success"
        });
        tableRef.value.refresh();
      });
    });
}

function setVersionSelect() {
  formulaVerGetList({
    start_page: 1,
    size: 0
  }).then(res => {
    formRef.value.setFormProps("version", {
      options: res.data
    });
  });
}

// endregion

// region 组件事件的集合
const search = () => {
  tableRef.value.refresh();
};

type ActionType = {
  key: ACTION_TYPE;
  row: StoreProp;
};
const actionClick = ({ key, row }: ActionType) => {
  console.log(key, row);
  switch (key) {
    case ACTION_TYPE.TADD:
    case ACTION_TYPE.EDIT:
      storeData.value = row ?? {};
      showModal.value = true;
      break;
    case ACTION_TYPE.DELETE:
      proxy.$auMessageBox
        .confirm(t("store_manage.form.confirm_close", { name: row.name }))
        .then(() => {
          updStoreStatusStore({
            store_status: 1,
            is_deactivate: true,
            idList: JSON.stringify([{ id: row.id }])
          }).then(res => {
            if (res.code === 200) {
              ElMessage.success(t("store_manage.form.close_success"));
              tableRef.value.refresh();
            }
          });
        });
      break;
    case ACTION_TYPE.TDELETE:
      multiDelete();
      break;
    case ACTION_TYPE.VIEW:
      router.push({
        name: "StoreManageDevice",
        query: {
          id: row.id,
          name: row.name
        }
      });
      break;
    case ACTION_TYPE.UPLOAD:
      console.log("打开导入页面");
      showUploadModal.value = true;
      break;
  }
};

const handleConfirm = (data: StoreProp) => {
  if (data.id) {
    updStore(data).then(res => {
      if (res.code === 200) {
        showModal.value = false;
        ElMessage({
          message: t("store_manage.form.edit_success"),
          type: "success"
        });
        tableRef.value.refresh();
      }
    });
  } else {
    addStore(data).then(res => {
      if (res.code === 200) {
        showModal.value = false;
        ElMessage({
          message: t("store_manage.form.add_success"),
          type: "success"
        });
        tableRef.value.refresh();
      }
    });
  }
};

//导入
const handleUploadConfirm = () => {
  console.log("开始导入");
  showUploadModal.value = false;
  /* ElMessage({
    message: "门店导入成功",
    type: "success"
  }); */
  tableRef.value.refresh();
};
// endregion

// region vue 生命周期及其他方法集合
onMounted(() => {
  getTreeSelect();
  setVersionSelect();
});
// endregion
</script>
